﻿
using Cms.Core.Data.UnitOfWork;
using Cms.Core.Infrastructure.Ui;
using System;
using System.Threading.Tasks;
using Cms.Core.Data.Model;
using Cms.Core.Application.IService;
using Cms.Core.Infrastructure.Runtime.Session;
using Cms.Core.Infrastructure.Extension;
using Cms.Core.Infrastructure.Helps;
using Cms.Core.Application.IService.UserInfo;
using System.Linq;

namespace Cms.Core.Application.Service
{
    /// <summary>
    /// 实体审计
    /// </summary>
    public class AuditEntryService : IAuditEntryService
    {

        private readonly IRepository<AuditEntry> _auditEntryRepository = null;
        private readonly ICmsSession _cmsSession = null;
        private readonly IUserService _userService = null;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="auditEntryRepository"></param>
        /// <param name="cmsSession"></param>
        /// <param name="userService"></param>
        public AuditEntryService(IRepository<AuditEntry> auditEntryRepository, ICmsSession cmsSession, IUserService userService)
        {
            _auditEntryRepository = auditEntryRepository;
            _cmsSession = cmsSession;
            _userService = userService;
        }




        /// <summary>
        /// 得到实体审计分页信息
        /// </summary>
        /// <param name="pageRequestData">分页请求数据</param>
        /// <returns></returns>
        public async Task<PageResult> GetAuditEntryPageDataAsync(PageRequestData pageRequestData)
        {
            pageRequestData.NotNull(nameof(pageRequestData));


            if (!_cmsSession.GetUserId().IsEmptyOrNullOrHasValue() && !_cmsSession.IsAdministrators())
            {

                pageRequestData.Filters.Add(new FilterInfo
                {
                    Field = "CreateUserId",
                    Value = _cmsSession.GetUserId()
                });
            }

            var filter = FilterHelp.ToFilterExpression<AuditEntry>(pageRequestData.Filters);
            filter.NotNull(nameof(filter));
            pageRequestData.OrderBy = "CreateTime descending";
            var userList = _userService.Users;
            var query = await _auditEntryRepository.QueryNotDelete.Where(filter).Join(userList, a => a.CreateUserId, u => u.Id, (a, u) => new {

                a.Id,
                a.EntityState,
                a.KeyValues,
                a.NewValues,
                a.TableName,
                a.OldValues,
                a.CreateTime,
                u.UserName,


            }).ToPageAsync(null, pageRequestData);
            return query.ToPageResult();
        }
    }
}
